﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Tools.Ribbon;
using System.Windows.Forms;
using Scrt;
using System.Threading;
using System.Diagnostics;
using DalMgr;
namespace WordAddIn2010
{
    /// <summary>
    /// 管理类
    /// </summary>
    public class SoftMgr
    {
        Ribbon _ribbon;
        Thread ThBack = null;
#region 构造析构函数

        /// <summary>
        /// 构造函数
        /// 初始化全局变量
        /// </summary>
        public SoftMgr()
        {
            Funcs.InitPubVal();
            ThBack = new Thread(BackgroundProc);
        }
        /// <summary>
        /// 析构函数
        /// 关闭word时卸载加载项
        /// </summary>
        ~SoftMgr()
        {
            for (int idx = 1; idx <= gValue.WordApp.AddIns.Count;idx++ )
            {
                //循环检测加载项，是否为本程序的加载项，如果时，则删除
                if (gValue.WordApp.AddIns[idx].Name == gValue.TEMPLATE_FILE_NAME)
                {
                    try
                    {
                        gValue.WordApp.AddIns[idx].Delete();
                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
            if (ThBack != null)
            {
                ThBack.Abort();
                ThBack = null;
            }
            gValue.WordApp = null;
        }
        private void BackgroundProc()
        {
            if (!Funcs.CheckNetConnection())
            {
                return;
            }
            if (Funcs.IsANewDay())
            {
                CheckUpdate();
            }
            SetDisHasNewVersion();
        }
        public void StrtBackground()
        {
            ThBack.Start();
        }
#endregion


#region 外部函数接口



        /// <summary>
        /// 初始化菜单
        /// </summary>
        /// <param name="_ribbon"></param>
        public void InitRibbon(Ribbon _ribbon)
        {
            this._ribbon = _ribbon;
            string strTemplate = gValue.SftCfgBaseDir  + gValue.TEMPLATE_FILE_NAME;
            if (!File.Exists(strTemplate))
            {
                //文件不存在，则复制原始文件，防止卸载的时候删除了
                string src = AppDomain.CurrentDomain.BaseDirectory + gValue.TEMPLATE_ORIGINAL_FILE_NAME;
                File.Copy(src,strTemplate,true);
            }
            _ribbon.grupAboutUs.Label = gValue.STUDIO_NAME;
            if (File.Exists(strTemplate))
            {
                try
                {
                    gValue.WordApp.AddIns.Add(strTemplate, true);
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    //加载时错误
                    ErrSet(_ribbon);
                    return;
                }
                SetAllBtnVisible(_ribbon,false);
                InitBtns(_ribbon);
            }
            else
            {
                ErrSet(_ribbon);
            }
            SetVisibleGroup(_ribbon);
        }


        public void ShowUserGuidFile()
        {
            string strPath = AppDomain.CurrentDomain.BaseDirectory  + gValue.USER_GUID_FILE;
            if (File.Exists(strPath))
            {
                try
                {
                    System.Diagnostics.Process.Start(strPath);
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                
            }
            else
            {
                MessageBox.Show("使用说明文件丢失", gValue.MSG_TITLE, MessageBoxButtons.OK);
            }
        }
        public void OpenUrl(string strUrl)
        {
            Process.Start(strUrl);
        }

#endregion

#region 内部函数

        /// <summary>
        /// 隐藏Group中的全部按钮
        /// </summary>
        /// <param name="ribbon"></param>
        private void SetAllBtnVisible(Ribbon ribbon,bool bVisible)
        {
            RibbonGroup ribbonGrp = null;
            for (int grpIdx = 0; grpIdx < gValue.GROUP_MAX_COUNT; grpIdx++)
            {
                ribbonGrp = GetGroup(ribbon, grpIdx);
                for (int i = 0; i < ribbonGrp.Items.Count; i++)
                {
                    ribbonGrp.Items[i].Visible = bVisible;
                }
            }
        }

        /// <summary>
        /// 初始化按钮
        /// </summary>
        /// <param name="_ribbon"></param>
        private void InitBtns(Ribbon _ribbon)
        {
            List<CategoryInfo> LstCat = new List<CategoryInfo>();
            LstCat.Add(new CategoryInfo());
            LstCat.Add(new CategoryInfo());
            LstCat.Add(new CategoryInfo());
            
            Word.Template objTemplate = GetTemplate();
            Word.BuildingBlock objBB;
            for (int idx = 1; idx <= objTemplate.BuildingBlockEntries.Count;idx++ )
            {
                objBB = objTemplate.BuildingBlockEntries.Item(idx);
                if (gValue.Dic_Cate.ContainsKey(objBB.Category.Name))
                {
                    LstCat[gValue.Dic_Cate[objBB.Category.Name]].AddItem(objBB.Name);
                }
            }
            //循环Grup
            CategoryInfo cateInfo;
            int btnIdx = 0;
            for (int idx = 0; idx < LstCat.Count;idx++ )
            {
                //循环Group中的按钮
                cateInfo = LstCat[idx];
                if (cateInfo.MenuItems.Count == 0)
                {
                    continue;
                }
                for (int i = 0; i < cateInfo.MenuItems.Count;i++ )
                {
                    //循环下一级按钮
                    RibbonMenu ribbonMenu = GetMenu(_ribbon,idx);
                    if (ribbonMenu == null)
                    {
                        _ribbon.grupAboutUs.Label = "菜单数量不够，请联系作者添加菜单";
                        continue;
                    }
                    ribbonMenu.Items.Clear();
                    ribbonMenu.Visible = true;
                    ribbonMenu.Label = cateInfo.MenuItems[i].category;
                    for (int j = 0; j < cateInfo.MenuItems[i].SubItems.Count; j++)
                    {
                        RibbonButton btn = _ribbon.Factory.CreateRibbonButton();
                        
                        if (Funcs.IsNum(cateInfo.MenuItems[i].SubItems[j]))
                        {
                            //如果子菜单字符串为数字，则和父级菜单一起显示
                            btn.Label = cateInfo.MenuItems[i].category + "_" + cateInfo.MenuItems[i].SubItems[j];
                        }
                        else
                        {
                            //否则只显示子菜单
                            btn.Label = cateInfo.MenuItems[i].SubItems[j];
                        }

                        btn.Name = gValue.BTN_ID_SUFFIX + btnIdx.ToString();
                        btn.Click +=new RibbonControlEventHandler(btn_Click);
                        ribbonMenu.Items.Add(btn);
                        btnIdx++;
                    }
                }
            }
           // MessageBox.Show(btnIdx.ToString());
        }

        /// <summary>
        /// 初始化Group的可见性
        /// 如果一个控件都没有可见，则Group不可见
        /// </summary>
        /// <param name="_ribbon"></param>
        private void SetVisibleGroup(Ribbon _ribbon)
        {
            RibbonGroup ribbonGrp;
            bool bVisible;
            for (int idx = 0; idx < gValue.GROUP_MAX_COUNT; idx++)
            {
                ribbonGrp= GetGroup(_ribbon, idx);
                bVisible = false;
                for (int i = 0; i < ribbonGrp.Items.Count; i++)
                {
                    if (ribbonGrp.Items[i].Visible)
                    {
                        bVisible = true;
                        break;
                    }
                }
                ribbonGrp.Visible = bVisible;
            }
        }

        /// <summary>
        /// 按钮单击事件
        /// 插入相应的内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Click(object sender, RibbonControlEventArgs e)
        {
            Word.BuildingBlock objBB;
            Word.Template objTemplate = GetTemplate();
            if (null == objTemplate)
            {
                MessageBox.Show("获取插入对象失败，请联系作者",gValue.MSG_TITLE);
                return;
            }
            //子菜单
            RibbonButton ribbonBnt = (RibbonButton)sender;
            string strBnt = ribbonBnt.Label;
            //父级菜单
            string strMenu = ((RibbonMenu)ribbonBnt.Parent).Label;
            string strName,str;

            //如果下一级的前面是父级菜单
            if ((strBnt.Length >= strMenu.Length) && (strBnt.Substring(0, strMenu.Length) == strMenu))
            {
                strName = strBnt;
                str = strBnt.Substring(strMenu.Length+1, strBnt.Length - strMenu.Length-1);
                if (!Funcs.IsNum(str))
                {
                    strName = strMenu + "_" + ribbonBnt.Label;
                }
            }
            else
            {
                strName = strMenu + "_" + ribbonBnt.Label;
            }
            try
            {
                objBB = objTemplate.BuildingBlockEntries.Item(strName);
            }
            catch 
            {
                objBB = null;
            }
            
            if (objBB != null)
            {
                if (gValue.RegRsult == RegisterResult.FAILED)
                {
                    MessageBox.Show("注册失败，请先注册该软件，谢谢", "提醒", MessageBoxButtons.OK);
                }
                objBB.Insert((Word.Range)gValue.WordApp.Selection.Range);
            }
            else
            {
                MessageBox.Show(strName + "  不存在\n -- 如有疑问，请与作者联系");
            }
            objBB = null;
            ribbonBnt = null;
            objTemplate = null;
            
        }
        /// <summary>
        /// 返回模板对象
        /// </summary>
        /// <returns></returns>
        private Word.Template GetTemplate()
        {
            for (int idx = 1; idx < gValue.WordApp.Templates.Count; idx++)
            {
                if (gValue.WordApp.Templates[idx].Name == gValue.TEMPLATE_FILE_NAME)
                {
                    return gValue.WordApp.Templates[idx];
                }
            }
            return null;
        }

        /// <summary>
        /// 返回一个菜单按钮对象
        /// </summary>
        /// <param name="_ribbon"></param>
        /// <param name="_grpIdx"></param>
        /// <returns></returns>
        private RibbonMenu GetMenu(Ribbon _ribbon ,int _grpIdx)
        {
            RibbonGroup ribbonGrp = GetGroup(_ribbon, _grpIdx);
            if (ribbonGrp == null)
            {
                return null;
            }
            for (int idx = 0; idx < ribbonGrp.Items.Count;idx++ )
            {
                if ((ribbonGrp.Items[idx].Name.IndexOf("menu") != -1 ) && (ribbonGrp.Items[idx].Visible == false) )
                {
                    return (RibbonMenu)ribbonGrp.Items[idx];
                }
            }
            return null;
        }

        /// <summary>
        /// 返回一个菜单Group对象
        /// </summary>
        /// <param name="_ribbon"></param>
        /// <param name="_grpIdx"></param>
        /// <returns></returns>
        private RibbonGroup GetGroup(Ribbon _ribbon, int _grpIdx)
        {
            RibbonGroup ribbonGrp = null;
            switch (_grpIdx)
            {
                case 0:
                    ribbonGrp = _ribbon.grupMath;
                    break;
                case 1:
                    ribbonGrp = _ribbon.grupPhy;
                    break;
                case 2:
                    ribbonGrp = _ribbon.grupChe;
                    break;
                default:
                    break;
            }
            return ribbonGrp;
        }

        /// <summary>
        /// 如果错误，则隐藏全部的菜单
        /// </summary>
        /// <param name="_ribbon"></param>
        private void ErrSet(Ribbon _ribbon)
        {
            _ribbon.grupPhy.Visible = false;
            _ribbon.grupMath.Visible = false;
            _ribbon.grupChe.Visible = false;
            _ribbon.grupAboutUs.Label = "文件出现错误，请联系作者";
        }
#endregion

#region 注册部分
        /// <summary>
        /// 注册部分
        /// </summary>
        public void RegSft()
        {
            
            if (gValue.RegRsult == RegisterResult.SUCCEED )
            {
                string str = "已经注册过了，需要重新注册吗？\r\n -- Yes:重新注册\r\n -- No:放弃";
                if (MessageBox.Show(str, gValue.MSG_TITLE, MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }
            }
            using (FrmRegister frm = new FrmRegister(gValue.SoftReg))
            {
                frm.ShowDialog();
            }
            gValue.RegRsult = gValue.SoftReg.RegResult;

            if (gValue.RegRsult == RegisterResult.FAILED)
            {
                this._ribbon.grupAboutUs.Label = "注册失败，请联系作者";
            }
        }
#endregion
        public SoftwareUpdateInfor CheckUpdate()
        {
            SoftwareUpdateInfor updateInfo = new SoftwareUpdateInfor(gValue.URL_SOFT_INFO, Funcs.GetSftVersion());
            
            gValue.SftwareDownloadUrl = updateInfo.UpdateUrl;
            SftDataMgr.WriteCfg(gValue.SFT_CFG,gValue.SFT_CFG_HAS_NEW_VERSION,updateInfo.NeedUpdate);
            return updateInfo;
        }
        public void SetDisHasNewVersion(bool bDis)
        {
            SftDataMgr.WriteCfg(gValue.SFT_CFG, gValue.SFT_CFG_HAS_NEW_VERSION, bDis);
            SetDisHasNewVersion();
        }
        public void SetDisHasNewVersion()
        {
            bool bDis = SftDataMgr.ReadBool(gValue.SFT_CFG, gValue.SFT_CFG_HAS_NEW_VERSION, false);
            this._ribbon.btnHasNewVersion.Visible = bDis;
            if (bDis)
            {
                this._ribbon.grupAboutUs.Label = "新版本出现了";
            }
            else
            {
                this._ribbon.grupAboutUs.Label = gValue.STUDIO_NAME;
            }
        }
    }
}
